const baseUrl = 'http://46ab786a.r28.cpolar.top/api';

// 获取所有药品信息
function getMedicines() {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${baseUrl}/commodities`,
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

// 提交订单
function submitOrder(order) {
  return new Promise((resolve, reject) => {
     // 深度克隆订单数据以避免引用问题
     const requestData = JSON.parse(JSON.stringify({
      ...order,
      // 添加时间戳防止缓存
      _timestamp: Date.now()
    }));
    // 再次检查请求数据
    if (requestData.orderItems && requestData.orderItems.length > 0) {
      requestData.orderItems.forEach(item => {
          if (!item.commodityId) {
              console.error('请求数据中的商品ID缺失:', item);
              reject(new Error('请求数据中的商品ID缺失'));
              return;
          }
      });
  }
    console.log('实际发送的请求数据:', requestData);
    wx.request({
      url: `${baseUrl}/pay/add`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
        // 'Authorization': 'Bearer ' + wx.getStorageSync('token') // 携带 Token
      },
      data: requestData,
      success: (res) => {
        console.log('API完整响应:', {
          status: res.statusCode,
          headers: res.header,
          data: res.data
        });
        
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          const error = new Error(
            res.data?.error || 
            res.data?.message || 
            `请求失败 (${res.statusCode})`
          );
          error.response = res;
          reject(error);
        }
      },
      fail: (err) => {
        console.error('网络请求失败详情:', err);
        reject(new Error(`网络错误: ${err.errMsg}`));
      }
    });
  });
}

// 根据订单号查询订单信息
function queryOrder(orderNumber) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${baseUrl}/orders/${orderNumber}`,
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}


module.exports = {
  getMedicines,
  submitOrder,
  queryOrder
};